package com.gzy.mylog.server;

import com.gzy.mylog.controller.paramer.LogPara;
import com.gzy.mylog.core.PageList;
import com.gzy.mylog.model.Log;
import com.gzy.mylog.model.User;
import com.gzy.mylog.repository.LogRepository;
import com.gzy.mylog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class LogServer {
    @Autowired
    LogRepository repository;
    @Autowired
    UserRepository userRepository;

    public List<Log> findAll(String username) {
        User user = userRepository.findUserByUsername(username);
        List<Log> allByUid = repository.findAllByUid(user.getId());
        return allByUid;
    }

    public Log add(Long userId, LogPara para) {
        Log log = new Log();

        log.setContent(para.getContent());
        log.setUid(userId);
        log.setCreateAt(System.currentTimeMillis());

        repository.save(log);

        return log;
    }

    public Log update(Long userId, Long id, LogPara para) {
        Log log = getLog(id);

        log.setContent(para.getContent());

        repository.save(log);

        return log;
    }

    private Log getLog(Long id) {
        Optional<Log> byId = repository.findById(id);
        if (byId.isEmpty()) {
            throw new RuntimeException("数据不存在");
        }
        return byId.get();
    }

    public void delete(Long userId, Long id) {
        Log log = getLog(id);
        if (userId != log.getUid()) {
            throw new RuntimeException("无权删除");
        }

        repository.deleteById(id);
    }

    // order = 1  Asc
    // order = 2  Desc

    public PageList<Log> page(Long id, Integer page, Integer size, Integer order) {

        int offset = (page - 1) * size;

        List<Log> pageList;

        if (order == 1) {
            pageList = repository.findAllByUidWithPage_Asc(id, offset, size);
        }else{
            pageList = repository.findAllByUidWithPage_Desc(id, offset, size);
        }


        PageList<Log> result = new PageList<>();
        result.setData(pageList);

        result.setCurrPage(page);

        int totalCount = repository.countByUid(id);

        int totalPage = totalCount / size;

        int mod = totalCount % size;
        if (mod > 0) {
            totalPage++;
        }

        result.setTotalPage(totalPage);

        return result;
    }
}
